//
//  SysUser.swift
//  icloud
//
//  Created by raymond on 2022/5/20.
//

import Foundation

struct TSysUser: Identifiable, Hashable, Codable {
  var id: UInt
  var username: String
  var realname: String
  var password: String
  var mobilePrefix: String
  var mobile: String
  var birthdayStr: String = ""
  var birthday: Date
  var sex: Int
  var status: Int
  
  enum CodingKeys: String, CodingKey {
    case id = "userId"
    case username
    case realname
    case password
    case mobilePrefix
    case mobile
    case birthdayStr = "birthday"
    case sex
    case status
  }
  
  init(id: UInt, username: String, realname: String, password: String, mobilePrefix: String, mobile: String, birthday: Date, sex: Int, status: Int){
    self.id = id
    self.username = username
    self.realname = realname
    self.password = password
    self.mobilePrefix = mobilePrefix
    self.mobile = mobile
    self.birthday = birthday
    self.sex = sex
    self.status = status
  }
  
  init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)
    let id = try container.decode(UInt.self, forKey: CodingKeys.id)
    let username = try container.decode(String.self, forKey: CodingKeys.username)
    let realname = try container.decode(String.self, forKey: CodingKeys.realname)
    let password = try container.decode(String.self, forKey: CodingKeys.password)
    let mobilePrefix = try container.decode(String.self, forKey: CodingKeys.mobilePrefix)
    let mobile = try container.decode(String.self, forKey: CodingKeys.mobile)
    
    let birthdayStr = try container.decode(String.self, forKey: CodingKeys.birthdayStr)
    let formatter = Formatter.str2date
    let birthday = formatter.date(from: birthdayStr)!
    
    let sex = try container.decode(Int.self, forKey: CodingKeys.sex)
    let status = try container.decode(Int.self, forKey: CodingKeys.status)
    
    self.init(id: id,username: username, realname: realname, password: password, mobilePrefix: mobilePrefix, mobile: mobile, birthday: birthday, sex: sex, status: status)
  }
  
  static func def()->TSysUser{
    return TSysUser(id: 0, username: "", realname: "", password: "", mobilePrefix: "86", mobile: "", birthday: Formatter.str2date.date(from: "2000-01-01 12:00:00") ?? Date(), sex: 0, status: 0)
  }
}
